package jrain.fw.cfg.classpath;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.utils.cls.ClassUtils;
import jrain.utils.collection.RDMap;
import jrain.utils.collection.RMap;
import jrain.utils.exception.ServiceException;
import jrain.utils.lang.StringUtils;
import jrain.utils.prop.PropUtils;

/**
 * <pre>
 * 作者：489088214@qq.com 
 * 描述： 配置文件解析
 * </pre>
 */
public class CfgClasspathPropParser implements CfgClasspathParser {

	public static Logger log = LoggerFactory.getLogger("cfg-classpath-prop");

	public Map<String, RMap<String, Object>> parserCfg() {
		Map<String, RMap<String, Object>> rsMap = new HashMap<>();
		Set<String> set = ClassUtils.getFiles("prop", ".conf");
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		set.forEach(path -> {
			try {
				parseFile(classLoader, path, rsMap);
			} catch (Exception e) {
				String msg = "prop parser error,file=%s";
				msg = String.format(msg, path);
				log.error(msg, e);
				throw new ServiceException(msg, e);
			}
		});
		log.info("prop parser finish!,{}", this.getClass().getSimpleName());
		return rsMap;
	}

	private void parseFile(ClassLoader classLoader, String path, Map<String, RMap<String, Object>> rsMap)
			throws Exception {
		Map<String, Object> map = PropUtils.getClasspathConf(path);
		log.debug("prop file={},data={}", path, map);
		String moduleName = StringUtils.trimNull(map.get("conf.module"));
		if (StringUtils.isEmpty(moduleName)) {
			log.warn("prop module is empty,file={}", path);
		} else {
			rsMap.put(moduleName, new RDMap<>(map));
		}
	}

}
